package com.qh.book.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.qh.book.dataobj.Book;
import com.qh.book.exception.BsException;
import com.qh.book.service.BookService;
import com.qh.book.enums.ResultEnum;

@Controller
@RequestMapping("/backstage/book")
public class BookController {
	
	@Autowired
	private BookService bookService;
	
	

	@GetMapping("/list")
	public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
							@RequestParam(value = "size", defaultValue = "10") Integer size,
							Map<String, Object> map) {
		
		//Sort sort = new Sort(new Order(Sort.Direction.DESC,"id"));
		Pageable pageable = new PageRequest(page - 1, size);
		Page<Book> bookPage = bookService.findAll(pageable);
		map.put("bookPage", bookPage);
		map.put("currentpage", page);
		map.put("size", size);
		return new ModelAndView("book/list", map);
	}
	/**
	 * 商品上架
	 * @param productId
	 * @param map
	 * @return
	 */
    @RequestMapping("/on_sale")
    public ModelAndView onSale(@RequestParam("bookid") String bookid,
                               Map<String, Object> map) {
        try {
        	bookService.onSale(bookid);
        } catch (BsException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/backstage/book/list");
            return new ModelAndView("common/error", map);
        }

        map.put("msg", ResultEnum.BOOK_ONSALE_SUCCESS.getMsg());
        map.put("url", "/backstage/book/list");
        return new ModelAndView("common/success", map);
    }
    
    /**
     * 商品下架
     * @param productId
     * @param map
     * @return
     */
    @RequestMapping("/off_sale")
    public ModelAndView offSale(@RequestParam("productId") String productId,
                               Map<String, Object> map) {
        try {
        	bookService.offSale(productId);
        } catch (BsException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/backstage/book/list");
            return new ModelAndView("common/error", map);
        }
        map.put("msg", ResultEnum.BOOK_OFFSALE_SUCCESS.getMsg());
        map.put("url", "/backstage/book/list");
        return new ModelAndView("common/success", map);
    }
}
